package com.xhs.annotation.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.xhs.annotation.annotation.ApiUrl;
import com.xhs.annotation.annotation.Xhs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.List;

/**
 * @desc： 测试自定义注解
 * @author： xhs
 * @date： 2021/5/14 9:49
 * @version： JDK 1.8
 */
@Slf4j
@RestController
public class TestController {

    @GetMapping("/test")
    @Xhs(name = "限流test接口", num = 1)
    @ApiUrl(name = "测试限流接口", url = "/test")
    public String test() {
        log.info("-----测试限流test接口-----");
        return "测试限流test接口";
    }

    /**
     * 获取有@ApiUrl注解的方法
     *
     * @return
     */
    @GetMapping("/getUrl")
    public List<String> getUrl() {
        List<String> apiList = CollectionUtil.newArrayList();
        SpringUtil.getApplicationContext().getBeansOfType(RequestMappingHandlerMapping.class).values()
                .forEach(requestMappingHandlerMapping -> requestMappingHandlerMapping.getHandlerMethods()
                        .forEach((key, value) -> {
                            ApiUrl api = value.getMethod().getAnnotation(ApiUrl.class);
                            if (ObjectUtil.isNotEmpty(api)) {
                                String apiUrl = api.url();
                                String apiName = api.name();
                                apiList.add(apiUrl + StrUtil.BRACKET_START + apiName + StrUtil.BRACKET_END);
                            }
                        }));

        return apiList;
    }
}
